package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.InfoHeaderDao;
import com.bestv.search.common.model.InfoHeader;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class InfoHeaderDaoHibernate extends GenericDaoHibernate<InfoHeader, Long> implements InfoHeaderDao {

    public InfoHeaderDaoHibernate() {
        super(InfoHeader.class);
    }

    @SuppressWarnings("unchecked")
    public List<InfoHeader> get(String name, String p_type) {
        String hql = "from InfoHeader where name = ? and p_type = ?";
        return super.getHibernateTemplate().find(hql, new String[]{name, p_type});
    }

    public  List<InfoHeader> get(String code, Boolean byCode){
        String hql = "from InfoHeader where code = ?";
        List<InfoHeader> list = super.getHibernateTemplate().find(hql, new String[]{code});
        return list;
    }

    @SuppressWarnings("unchecked")
    public InfoHeader get(String code) {
        String hql = "from InfoHeader where code = ?";
        List<InfoHeader> list = super.getHibernateTemplate().find(hql, new String[]{code});
        return list == null || list.size() == 0 ? null : list.get(0);
    }

    @SuppressWarnings("unchecked")
    public List<InfoHeader> getAllValidHeader() {
        String hql = "from InfoHeader where status = 1";
        return super.getHibernateTemplate().find(hql);
    }

    public String getDefaultCodeByHeaderId(long headerId) {
        String hql = "select info.code from info inner join infoHeader_item  on info.id=infoHeader_item.info_id"
                + " where infoHeader_item.info_header_id = ? and update_flag<>2 order by info.hd asc, infoHeader_item.info_order asc";
        Session session = null;
        try {
            Query query = getSession().createSQLQuery(hql);
            query.setLong(0, headerId);
            query.setMaxResults(1);
            Object obj = query.uniqueResult();
            if (obj != null) {
                return obj.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return null;
    }

    public int getTotalHitCountByHeaderId(long headerId) {
        String hql = "select sum(info.hit_count) from info inner join infoHeader_item  on info.id=infoHeader_item.info_id"
                + " where infoHeader_item.info_header_id = ? and update_flag<>2";
        Session session = null;
        try {
            Query query = getSession().createSQLQuery(hql);
            query.setLong(0, headerId);
            Object obj = query.uniqueResult();
            if (obj != null) {
                return Integer.valueOf(obj.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return 0;
    }

    public int getItemCountByHeaderId(long headerId) {
        String hql = "select count(*) from info inner join infoHeader_item  on info.id=infoHeader_item.info_id"
                + " where infoHeader_item.info_header_id = ? and update_flag<>2";
        Session session = null;
        try {
            Query query = getSession().createSQLQuery(hql);
            query.setLong(0, headerId);
            Object obj = query.uniqueResult();
            if (obj != null) {
                return Integer.valueOf(obj.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return 0;
    }

    @SuppressWarnings("unchecked")
    public List<InfoHeader> getHeadersByUpdateTime(Date updateTime) {
        String hql = "from InfoHeader where update_time_for_index >=:updateTimeForIndex order by update_time_for_index asc";
        Session session = null;
        List<InfoHeader> headers = null;
        try {
            Query query = getSession().createQuery(hql);
            query.setTimestamp("updateTimeForIndex", updateTime);
            headers = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return headers;
    }

    @SuppressWarnings("unchecked")
    public List<InfoHeader> getInfoHeaderLikeName(String name, String headerType, int start, int limit) {
        String hql = "from InfoHeader where name like ? and  headerType = ?";

        Session session = null;
        try {
            session = getSession();
            Query query = session.createQuery(hql);
            query.setString(0, "%" + name + "%");
            query.setString(1, headerType);
            query.setFirstResult(start);
            query.setMaxResults(limit);
            return query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return null;
    }

    public int getInfoHeaderCountLikeName(String name, String headerType) {
        String hql = "select count(*) from InfoHeader where name like ? and  headerType = ?";

        Session session = null;
        try {
            session = getSession();
            Query query = session.createQuery(hql);
            query.setString(0, "%" + name + "%");
            query.setString(1, headerType);

            Object obj = query.uniqueResult();
            if (obj == null) {
                return 0;
            } else {
                return Integer.valueOf(obj.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return 0;
    }

    public boolean existOnlineInfosForHeaderId(long headerId) {
        String sql = "select info.id from infoHeader_item inner join info on info.id =infoHeader_item.info_id"
                + " where info.update_flag!=2 and infoHeader_item.info_header_id = ? ";

        Session session = null;
        try {
            session = getSession();
            Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            query.setLong(0, headerId);
            query.setMaxResults(1);

            Object obj = query.uniqueResult();
            if (obj == null) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return false;
    }

    public List<Map<String, String>> getInfoHeaderItemByHeaderId(long headerId) {
        String hql = "select info.id, info.name, info.content_flag, info.content_version, infoHeader_item.info_order, infoHeader_item.description"
                + " from info inner join infoHeader_item on info.id=infoHeader_item.info_id"
                + " where infoHeader_item.info_header_id = ? and update_flag<>2 order by infoHeader_item.info_order asc";
        Session session = null;
        try {
            Query query = getSession().createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            query.setLong(0, headerId);

            @SuppressWarnings("unchecked")
            List<Map<String, String>> results = query.list();
            if (results != null && results.size() > 0) {
                return results;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return null;
    }
}